package com.huawei.esdk.tp.interceptor;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;

import com.huawei.esdk.platform.common.ThreadLocalHolder;
import com.huawei.esdk.tp.common.constants.InfoKeys;

public class TPOutInterceptor extends AbstractPhaseInterceptor<Message>
{
    private static final Logger logger = Logger
            .getLogger(TPOutInterceptor.class);

    public TPOutInterceptor()
    {
        super(Phase.PRE_STREAM);
    }

    public void handleMessage(Message message) throws Fault
    {
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>) message
                .get(Message.PROTOCOL_HEADERS);
        if (headers == null)
        {
            headers = new HashMap<String, List<String>>();
        }

        try
        {
            if (null != ThreadLocalHolder.get())
            {
                headers.put(
                        "Set-Cookie",
                        Collections.singletonList("JSESSIONID="
                                + ThreadLocalHolder
                                        .get()
                                        .getEntities()
                                        .get(InfoKeys.SDK_SESSION_ID.toString())));
                message.put(Message.PROTOCOL_HEADERS, headers);
                
                ThreadLocalHolder.unset();
            }

        }
        catch (Exception e)
        {
            logger.error("", e);
            throw new Fault(e);
        }

    }

}
